package com.tianji.learning.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianji.api.client.course.CatalogueClient;
import com.tianji.api.client.course.CourseClient;
import com.tianji.api.dto.course.CataSimpleInfoDTO;
import com.tianji.api.dto.course.CourseSimpleInfoDTO;
import com.tianji.api.dto.trade.OrderBasicDTO;
import com.tianji.common.domain.dto.PageDTO;
import com.tianji.common.domain.query.PageQuery;
import com.tianji.common.exceptions.BadRequestException;
import com.tianji.common.exceptions.BizIllegalException;
import com.tianji.common.utils.*;
import com.tianji.learning.domain.dto.LearningPlanDTO;
import com.tianji.learning.domain.po.LearningLesson;
import com.tianji.learning.domain.po.LearningRecord;
import com.tianji.learning.domain.vo.LearningLessonVO;
import com.tianji.learning.domain.vo.LearningPlanPageVO;
import com.tianji.learning.domain.vo.LearningPlanVO;
import com.tianji.learning.enums.LessonStatus;
import com.tianji.learning.enums.PlanStatus;
import com.tianji.learning.mapper.LearningLessonMapper;
import com.tianji.learning.mapper.LearningRecordMapper;
import com.tianji.learning.service.ILearningLessonService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.tianji.learning.enums.LessonStatus.EXPIRED;

/**
 * <p>
 * 学生课程表 服务实现类
 * </p>
 *
 * @author yang
 * @since 2024-06-20
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class LearningLessonServiceImpl extends ServiceImpl<LearningLessonMapper, LearningLesson> implements ILearningLessonService {

    private final CourseClient courseClient;
    private final CatalogueClient catalogueClient;
    private final LearningRecordMapper recordMapper;



    @Override
    public void addUserLessons(Long userId, List<Long> courseIds) {

        //获得课程信息
        List<CourseSimpleInfoDTO> courseSimple = courseClient.getSimpleInfoList(courseIds);
        //判断课程信息不为空
        if (CollUtils.isEmpty(courseSimple)) {
            //课程不存在，无法添加到课表
            log.error("课程信息不存在，无法添加到课表");
            return;
        }

        //创建实体集合
        List<LearningLesson> list = new ArrayList<>(courseSimple.size());
        //遍历课程信息
        for (CourseSimpleInfoDTO course : courseSimple) {
            //创建实体
            LearningLesson learningLesson = new LearningLesson();
            //设置userID
            learningLesson.setUserId(userId);
            //设置课程ID
            learningLesson.setCourseId(course.getId());
            //过期时间
            Integer validDuration = course.getValidDuration();
            if (validDuration != null && validDuration > 0) {
                learningLesson.setExpireTime(LocalDateTime.now().minusMonths(validDuration));
                //添加到集合
                list.add(learningLesson);
            }

            //批量添加到数据库
            saveBatch(list);

        }
    }

    @Override
    public PageDTO<LearningLessonVO> PageAll(PageQuery pageQuery) {

        //拿到了用户ID
        Long user = UserContext.getUser();
        log.info("分页查询学生课程表，userId:{}", user);

        //分页查询
        Page<LearningLesson> page = lambdaQuery()
                .eq(LearningLesson::getUserId, user) // where user_id = #{userId}
                .page(pageQuery.toMpPage("latest_learn_time", false));

        //获取课程信息
        Map<Long, CourseSimpleInfoDTO> cMap = queryCourseSimpleInfoList(page.getRecords());

        //封装成VO
        ArrayList<LearningLessonVO> learningLessonVOs = new ArrayList<>();
        for (LearningLesson record : page.getRecords()) {
            LearningLessonVO learningLessonVO = BeanUtils.toBean(record, LearningLessonVO.class);
            CourseSimpleInfoDTO courseSimpleInfoDTO = cMap.get(record.getCourseId());
            learningLessonVO.setCourseName(courseSimpleInfoDTO.getName());
            learningLessonVO.setCourseCoverUrl(courseSimpleInfoDTO.getCoverUrl());
            learningLessonVO.setSections(courseSimpleInfoDTO.getSectionNum());
            learningLessonVOs.add(learningLessonVO);
        }

        return PageDTO.of(page, learningLessonVOs);
    }

    @Override
    public LearningLessonVO getNowLesson() {
        //拿到用户ID
        Long user = UserContext.getUser();
        if (user == null) {
            log.error("用户未登录，无法查询当前正在学习的课程");
            return null;
        }
        //查询当前正在学习的课程
        LearningLesson one = lambdaQuery()
                .eq(LearningLesson::getUserId, user)
                .eq(LearningLesson::getStatus, 1)
                .orderByDesc(LearningLesson::getLatestLearnTime)
                .last("limit 1").one();
        //补全信息
        if (one == null) {
            log.error("用户未学习任何课程");
            return null;
        }

        //提取小节id
        ArrayList<Long> sectionIds = new ArrayList<>();
        sectionIds.add(one.getLatestSectionId());


        ArrayList<LearningLesson> list = new ArrayList();
        list.add(one);
        Map<Long, CourseSimpleInfoDTO> courseMap = queryCourseSimpleInfoList(list);
        CourseSimpleInfoDTO course = courseMap.get(one.getCourseId());

        LearningLessonVO lessonVO = BeanUtils.toBean(one, LearningLessonVO.class);

        lessonVO.setCourseName(course.getName());
        lessonVO.setSections(course.getSectionNum());
        lessonVO.setCourseCoverUrl(course.getCoverUrl());

        Integer courseAmount = lambdaQuery()
                .eq(LearningLesson::getUserId, user)
                .count();
        lessonVO.setSections(courseAmount);


        //根据小节Id找信息

        List<CataSimpleInfoDTO> cataSimpleInfoDTOS = catalogueClient.batchQueryCatalogue(sectionIds);
        CataSimpleInfoDTO cata = cataSimpleInfoDTOS.get(0);
        lessonVO.setLatestSectionName(cata.getName());
        lessonVO.setLatestSectionIndex(cata.getCIndex());

        return lessonVO;
    }

    @Override
    public void refundUserLessons(List<Long> courseIds) {

        Long user = UserContext.getUser();

        if (user == null) {
            log.error("用户未登录，无法查询当前正在学习的课程");
            return;
        }

        if (CollUtils.isEmpty(courseIds)) {
            log.error("课程信息不存在，无法添加到课表");
            return;
        }

        lambdaUpdate()
                .in(LearningLesson::getCourseId, courseIds)
                .eq(LearningLesson::getUserId, user)
                .remove();

    }

    @Override
    public Long getLessonId(Long courseId) {
        Long user = UserContext.getUser();
        if (user == null) {
            log.error("用户未登录，无法查询当前正在学习的课程");
            return null;
        }
        ArrayList<Long> courseIds = new ArrayList<>();
        courseIds.add(courseId);
        List<CourseSimpleInfoDTO> simpleInfoList = courseClient.getSimpleInfoList(courseIds);
        CourseSimpleInfoDTO courseSimpleInfoDTO = simpleInfoList.get(0);
        if (courseSimpleInfoDTO.getStatus().equals(EXPIRED)){
            return null;
        }
        LearningLesson one = lambdaQuery()
                .eq(LearningLesson::getCourseId, courseId)
                .eq(LearningLesson::getUserId, user)
                .one();
        Long id = null;
        return one.getId();
    }

    @Override
    public LearningLessonVO getLessonStatus(Long courseId) {
        Long user = UserContext.getUser();
        if (user == null) {
            log.error("用户未登录，无法查询当前正在学习的课程");
            return null;
        }
        LearningLesson one = lambdaQuery()
                .eq(LearningLesson::getCourseId, courseId)
                .eq(LearningLesson::getUserId, user)
                .one();

        LearningLessonVO learningLessonVO = BeanUtils.toBean(one, LearningLessonVO.class);
        return learningLessonVO;
    }

    @Override
    public Integer countLearningLessonByCourse(Long courseId) {
        Long user = UserContext.getUser();
        if (user == null) {
            log.error("用户未登录，无法查询当前正在学习的课程");
            return null;
        }
        Integer count = lambdaQuery()
                .eq(LearningLesson::getCourseId, courseId)
                .eq(LearningLesson::getUserId, user)
                .count();
        return count;
    }

    @Override
    public void createPlans(LearningPlanDTO planDTO) {
        // 1、查询课表信息
        LearningLesson lesson = getOne(buildUserIdAndCourseIdWrapper(UserContext.getUser(), planDTO.getCourseId()));
        AssertUtils.isNotNull(lesson,"课程信息不存在");

        // 2、更新学习计划数据
        this.lambdaUpdate()
                .set(LearningLesson::getWeekFreq, planDTO.getFreq())
                .set(lesson.getPlanStatus() == PlanStatus.NO_PLAN,LearningLesson::getPlanStatus, PlanStatus.PLAN_RUNNING)
                .eq(LearningLesson::getId, lesson.getId())
                .update();
    }

    @Override
    public LearningPlanPageVO queryMyPlans(PageQuery pageQuery) {
        LearningPlanPageVO vo = new LearningPlanPageVO();
        // 1、获取当前登录用户
        Long userId = UserContext.getUser();

        // 2、分页查询我的课表
        // SELECT * FROM `learning_lesson` WHERE user_id = 2 AND `status` IN (0,1) AND plan_status = 1
        //ORDER BY latest_learn_time DESC LIMIT 0,2;
        Page<LearningLesson> pageResult = this.lambdaQuery()
                .eq(LearningLesson::getUserId, userId)
                .eq(LearningLesson::getPlanStatus, PlanStatus.PLAN_RUNNING)
                .in(LearningLesson::getStatus, LessonStatus.NOT_BEGIN, LessonStatus.LEARNING)
                .page(pageQuery.toMpPage("latest_learn_time", false));
        List<LearningLesson> records = pageResult.getRecords();
        if(ObjectUtil.isEmpty(records)){
            return vo.emptyPage(pageResult);
        }

        // 3、根据课程ID集合查询课程信息
        Map<Long, CourseSimpleInfoDTO> courseInfoMap = queryCourseInfoAnd2Map(records);

        // 4、统计学习记录中本周学习小节数据
        //SELECT r.`lesson_id`,COUNT(*) AS num  FROM `learning_record` r WHERE r.`user_id` = 2 AND r.`finished` = 1
        // AND r.`finish_time` BETWEEN '2024-06-21 00:00:00' AND '2024-06-22 23:59:59' GROUP BY r.`lesson_id`

        // 4.1、获取本周开始、结束日期
        LocalDateTime begin = DateUtils.getWeekBeginTime(LocalDate.now());
        LocalDateTime end = DateUtils.getWeekEndTime(LocalDate.now());

        // 4.2、发起分组统计
        QueryWrapper<LearningRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .select("lesson_id as id,COUNT(*) AS num")
                .eq("user_id",userId)
                .eq("finished",true)
                .between("finish_time",begin,end)
                .groupBy("lesson_id");
        List<Map<String, Object>> mapList = recordMapper.selectMaps(queryWrapper);
        Map<Long, Long> learnedSectionNumMap = mapList.stream().collect(Collectors.toMap(c -> (Long) c.get("id"), c -> (Long) c.get("num")));

        // 5、循环课表数据，进行数据填充补齐
        List<LearningPlanVO> voList = new ArrayList<>(records.size());
        for (LearningLesson record : records) {
            // 5.1、拷贝po数据至vo
            LearningPlanVO learningPlanVO = BeanUtils.copyBean(record, LearningPlanVO.class);

            // 5.2、填充课程数据
            CourseSimpleInfoDTO courseInfo = courseInfoMap.get(record.getCourseId());
            if(ObjectUtil.isNotEmpty(courseInfo)){
                learningPlanVO.setCourseName(courseInfo.getName());
                learningPlanVO.setSections(courseInfo.getSectionNum());
            }

            // 5.3、填充本周已学习小节数
            learningPlanVO.setWeekLearnedSections(learnedSectionNumMap.getOrDefault(record.getId(),0L).intValue());

            // 5.4、添加vo至vo集合
            voList.add(learningPlanVO);
        }

        // 6、计算本周计划学习的总小节数（可以直接在mapper层写sql查询，更方便，目前这种写法也要会）
        LearningLesson lesson = this.query()
                .select("sum(week_freq) as total_weekfreq")
                .eq("user_id", userId)
                .eq("plan_status", PlanStatus.PLAN_RUNNING)
                .in("status", LessonStatus.NOT_BEGIN, LessonStatus.LEARNING)
                .one();

        // 7、计算本周已学习的总小节数
        Integer weekFinished = this.recordMapper.selectCount(
                Wrappers.<LearningRecord>lambdaQuery()
                        .eq(LearningRecord::getUserId, userId)
                        .eq(LearningRecord::getFinished, true)
                        .between(LearningRecord::getFinishTime, begin, end)
        );

        // 8、封装Vo并返回
        vo.setWeekTotalPlan(lesson.getTotalWeekfreq());
        vo.setWeekFinished(weekFinished);
        vo.setWeekPoints(null);  //TODO 本周学习积分数

        return vo.pageInfo(pageResult.getTotal(), pageResult.getPages(), voList);
    }
    private Map<Long, CourseSimpleInfoDTO> queryCourseInfoAnd2Map(List<LearningLesson> records) {
        Set<Long> ids = records.stream().map(LearningLesson::getCourseId).collect(Collectors.toSet());
        List<CourseSimpleInfoDTO> courseInfoList = courseClient.getSimpleInfoList(ids);
        if(ObjectUtil.isEmpty(courseInfoList)){
            throw new BizIllegalException("课程信息不存在");
        }
        Map<Long, CourseSimpleInfoDTO> courseInfoMap = courseInfoList.stream().collect(Collectors.toMap(c -> c.getId(), Function.identity()));
        return courseInfoMap;
    }

    public LearningLesson queryLessonByCourseIdAndUserId(Long courseId, Long userId) {
        return getOne(buildUserIdAndCourseIdWrapper(userId, courseId));
    }
    private LambdaQueryWrapper<LearningLesson> buildUserIdAndCourseIdWrapper(Long userId, Long courseId) {
        LambdaQueryWrapper<LearningLesson> queryWrapper = new QueryWrapper<LearningLesson>()
                .lambda()
                .eq(LearningLesson::getUserId, userId)
                .eq(LearningLesson::getCourseId, courseId);
        return queryWrapper;
    }
    //获取课程信息
    private Map<Long, CourseSimpleInfoDTO> queryCourseSimpleInfoList(List<LearningLesson> records) {
        //获取课程id集合
        Set<Long> cIds = records.stream().map(LearningLesson::getCourseId).collect(Collectors.toSet());
        //查询课程信息
        List<CourseSimpleInfoDTO> courseSimpleInfoList = courseClient.getSimpleInfoList(cIds);
        //判断课程信息是否为空
        if (CollUtils.isEmpty(courseSimpleInfoList)) {
            // 课程不存在，无法添加
            throw new BadRequestException("课程信息不存在！");
        }
        //封装成map
        Map<Long, CourseSimpleInfoDTO> cMap = courseSimpleInfoList.stream()
                .collect(Collectors.toMap(CourseSimpleInfoDTO::getId, c -> c));
        return cMap;
    }
}